<template>
	<div class="book-records">
		<div class="col-md-9 records-bg" ref="listContent">
			<ul class="cbp_tmtimeline">
				<template v-if="data.records && data.records.length">
			    	<li v-for="(item,index) in data.records">
				        <time class="cbp_tmtime">
				        	<span>{{item.created_at[1]}}</span>
				        	<span>{{item.created_at[0]}}</span>
				        </time>
				        <div class="cbp_tmicon"></div>
				        <div class="cbp_tmlabel">
				        	<div class="record-func" v-if="isAdmin && item.hasOwnProperty('status')">
				      			<span @click="modifyRecord(item, index)">修改</span>
				      			<span @click="changeStatus(item, index)">{{item.status ? '隐藏':'显示'}}</span>
				      		</div>
				          	<div class="cbp_tmlabel_title">{{item.title}}</div>
				          	<p class="article-content" @click="showImage($event)" v-html="toMarkDown(item.content)"></p>
				      	</div>
			      	</li>
				</template>
				<template v-else>
					<li>
				        <time class="cbp_tmtime">
				        	<span></span>
				        	<span></span>
				        </time>
				        <div class="cbp_tmicon"></div>
				        <div class="cbp_tmlabel">
				          	<p class="article-content">还没有笔记哦~</p>
				      	</div>
			      	</li>
				</template>
		      	<li v-if="isAdmin">
		      		<time class="cbp_tmtime" v-if="time">
			        	<span>{{time[1]}}</span>
			        	<span>{{time[0]}}</span>
			        </time>
			        <div class="cbp_tmicon"></div>
			      	<div class="cbp_tmlabel record-textarea" style="padding-bottom: 8px">
				    	<input type="text" v-model="form.title" ref="recordTitle" class="form-control record-title" placeholder="输入笔记标题">
						<textarea class="form-control" placeholder="支持部分markdown语法，请勿发布敏感、负能量、不友善等内容..." name="CmtText" cols="30" rows="5" v-model="form.content" ref="replyBox"></textarea>
						<div class="record-group text-right">
							<span>ctrl+enter</span>
							<input type="button" class="btn btn-primary reply-btn" value="回复" @click="saveRecord">
						</div>
						<div class="preview-box" v-show="form.content">
							<p v-html="toMarkDown(form.content)"></p>
						</div>
					</div>
		      	</li>
		    </ul>
		</div>
		<div class="col-md-3">
			<div class="panel panel-default book-info text-center">
				<div class="book-image">
					<img :src="data.image">
				</div>
				<div class="book-footer">{{data.title}}</div>
			</div>
			<div class="panel panel-default record-menu" :class="{'menu-fixed':fixMenu}" ref="menu" v-if="menu.length">
				<div class="panel-heading text-center">
                    <h3 class="panel-title">目录</h3>
                </div>
				<div class="item-menus">
					<span v-for="(item,index) in menu" :class="{active:index === checked}" @click="scrollToLi(index)" v-show="showItem(index)">{{item.title}}</span>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import {deepCopy} from 'common/func'
	import {getScrollTop, scrollTo} from 'common/dom'
    import {mapGetters,mapMutations} from 'vuex'
    import Marked from 'common/convertMarkDown'

	export default {
		computed: {
			isAdmin() {
				return this.userInfo.hash
			},
            ...mapGetters([
              'userInfo',
              'login'
            ])
        },
		data() {
			return {
				data: [],
				form: {
					title: '',
					content: ''
				},
				url: 'note',
				menuTop: -1,
				fixMenu: false,
				menuLength: 0,
				id: 0,
				index: -1,
				updateId: -1,
				menu: new Array(),
				checked: 0
			}
		},
		created() {
			if(this.isAdmin) {
				this.url = 'completeNote'
			}
			this.time = this.getNowData()
			window.addEventListener('scroll', this.handleScroll)
			this.routerChange()
		},
		methods: {
			getNowData() {
				let data = new Date()
				return[data.getFullYear(),data.getMonth() + 1 + '-' + data.getDate()]
			},
			showImage(event) {
				if(event.target.nodeName === 'IMG'){
					this.setShowImage(event.target.src)
				}
			},
			routerChange() {
				this.id = parseInt(this.$route.params.id)
				scrollTo(0)
				this.__getData()
			},
			toMarkDown(string) {
				return Marked(string, { sanitize: true })
			},
			showItem(index) {
				if(this.checked < 4) {
					return index < 7
				}
				if(this.checked > this.menuLength - 4) {
					return index > this.menuLength - 8
				}

				return this.checked - 4 < index && this.checked + 4 > index
			},
			handleScroll() {
				if(!this.menuLength) {
					return false
				}
				let scrollTop = getScrollTop()
				if(scrollTop - this.menuTop > 45) {
					if(!this.fixMenu) {
						this.fixMenu = true
					}
				} else {
					if(this.fixMenu) {
						this.fixMenu = false
					}
				}
				if(scrollTop < this.menu[0].offsetTop) {
					this.checked === 0 ? '': this.checkActived(0)
					return false;
				}
				if(scrollTop > this.menu[this.menuLength - 1].offsetTop) {
					this.checked === this.menuLength - 1 ? '': this.checkActived(this.menuLength - 1)
					return false;
				}
				this.menu.forEach((item, index) => {
					if(scrollTop > item.offsetTop && scrollTop <= this.menu[index + 1].offsetTop){
						this.checked = index
					}
				})
			},
			checkActived(checked) {
				this.checked = checked
			},
			scrollToLi(checked) {
				this.checkActived(checked)
				scrollTo(this.menu[checked].offsetTop + 35)
			},
			appendData(data) {
				this.data.records ? this.data.records.push(data): this.data.records = [data]
				this.refreshMenuTop();
			},
			refreshMenuTop() {
				if(this.menu.length) {
					let _this= this
					setTimeout(()=> {
						_this.createMenu()
					},50)
				}
			},
			createMenu() {
				this.menuTop = this.$refs.menu.offsetTop
				let content = this.$refs.listContent
				let lis = content.getElementsByTagName("li")
				let lisLength = lis.length
				let length = lisLength === this.menu.length ? lisLength : lisLength - 1
				for (let i = 0; i < length; i++) {
					this.menu[i].offsetTop = lis[i].offsetTop
					this.menu[i].active = 0
				}
				this.menuLength = this.menu.length
			},
			modifyRecord(item, index) {
				this.form.title = item.title
				this.form.content = item.content
				this.updateId = item.id
				this.index = index
				this.$refs.recordTitle.focus()
			},
			changeStatus(item, index) {
				let status = item.status
				this.$http.patch('changeStatus/'+item.id, {status:!status}).then((response) => {
					this.data.records[index].status = !status
				})
			},
			filterData() {
				if(this.form.title == "") {
					this.$message('标题不能为空')
					return false
				}
				if(this.form.title.length > 18) {
					this.$message('标题长度不能大于18')
					return false
				}
				if(this.form.content == "") {
					this.$message('内容不能为空')
					return false
				}
				return true
			},
			saveRecord() {
				if(!this.filterData()) {
					return false
				}
				let method,form,url,data,msg
				if(this.updateId != -1) {
					url = 'record/' + this.updateId
					method = 'patch'
					form = this.form
					msg = '修改'
				} else {
					url = 'record'
					method = 'post'
					form = Object.assign({note_id: this.id},this.form)
					msg = '新增'
				}
				this.$http[method](url, form).then((response)=> {
					data = response.data
					delete data.updated_at
					this.updateId == -1 ? this.appendData(data) : this.data.records[this.index] = data
					this.$message(msg+'成功')
					this.updateId = -1
					this.index = -1
					this.form.title = ""
					this.form.content = ""
				})
			},
			__getData() {
				this.$http.get(this.url + '/' + this.id).then((response)=> {
					this.setDataReady(true)
					this.data = response.data
					this.menu = this.data.records
					this.refreshMenuTop()
				})
			},
			...mapMutations({
             	setDataReady: 'SET_DATA_READY',
              	setDataReady: 'SET_DATA_READY'
            })
		},
		watch: {
			'$route': 'routerChange'
		}
	}
</script>

<style lang="scss" scope>
	.book-records {
		.book-info {
			padding: 20px 15px;
			background-color: #fff;
			border-bottom: 1px solid #f6f6f6;
			.book-image {
				margin-bottom: 15px;
				>img {
					max-width: 100%;
					max-height: 100%;
				}
			}
		}
		.cbp_tmtimeline {
			padding:0;
			list-style:none;
			position:relative;
			&:before {
				content:'';
				position:absolute;
				top:0;
				bottom:0;
				width:5px;
				background: #dcdcdc;
				left:158px;
				margin-left:-10px;
			}
			>li {
				position:relative;
				.cbp_tmtime {
					display:block;
					width:118px;
					padding-right:30px;
					position:absolute;
					margin-left:30px;
					span {
						display:block;
						text-align:right;
						&:first-child {
							font-size:14px;
							color: #D2D2D2;
						}
						&:last-child {
							font-size:22px;
							color: #DCDCDC;
						}
					}
				}
				.cbp_tmlabel {
					margin:0 0 15px 180px;
					background: #fff;
					color: #333;
					padding:30px 25px;
					position:relative;
					border-radius:5px;
					min-height:150px;
					.cbp_tmlabel_title {
						margin-top:0px;
						padding:0 0 10px 0;
						font-size:16px;
						text-shadow:rgba(128,128,128,0.71) 1px 1px 1px;
						&:after {
							right:100%;
							border:solid transparent;
							content:" ";
							height:0;
							width:0;
							position:absolute;
							pointer-events:none;
							border-right-color:#fff;
							border-width:10px;
							top:10px;
						}
					}
					.record-func {
						position: absolute;
						right: 0;
						top: 0;
						padding: 5px 10px;
						color: #dcdcdc;
						>span {
							cursor: pointer;
							&:hover {
								color: #FFCC00;
							}
						}
					}
					.record-title {
						padding: 0 15px;
						margin-bottom: 10px;
					}
					.form-control {
					    margin: 0;
					    margin-bottom: 10px;
					    padding: 10px 15px;
					    width: 100%;
					    border-radius: 4px;
					    background-color: #fff;
					    border: 1px solid #c1c1c1;
					    word-wrap: break-word;
				    	resize: horizontal;
					}
					.btn-primary {
					    background-color: #f4645f;
					    border-color: #f93e38;
					    border-radius: 4px !important;
					    &:hover {
						    background-color: #f54944;
						    border-color: #f11b14;
						}
						&:focus {
						    background-color: #f54944;
						    border-color: #f11b14;
						    outline: none;
						}
						&:active {
							background-color: #f4645f;
					    	border-color: #f93e38;
						}
					}
					.preview-box {
						padding: 10px;
						margin-top: 10px;
					    border: dashed 1px;
					    background: #faf5eb;
					}
				}
				.cbp_tmicon {
					width:10px;
					height:10px;
					font-family:'ecoico';
					speak:none;
					font-style:normal;
					font-weight:normal;
					font-variant:normal;
					text-transform:none;
					font-size:1.4em;
					line-height:40px;
					-webkit-font-smoothing:antialiased;
					position:absolute;
					color:#fff;
					background: #dcdcdc;
					border-radius:50%;
					box-shadow:0 0 0 3px #f5f5f5;
					text-align:center;
					left:170px;
					top:15px;
					margin:0 0 0 -25px;
				}
				.cbp_tmtime {
					-webkit-transition:all 1s;
					-moz-transition:all 1s;
					-o-transition:all 1s;
				}
				&:hover {
					.cbp_tmicon {
						box-shadow:0 0 0 3px #fff;
					}
					.cbp_tmtime {
						background:#dcdcdc;
						border-radius:20px 0 0 20px;
						span {
							color:#51514f;
						}
					}
				}
			}
		}
		.panel-default {
			.panel-heading {
				background-color: #fff;
				border-bottom: 1px solid #f6f6f6;
			}
		}
		.record-menu {
			.item-menus {
				padding: 5px 10px;
				>span {
					display: block;
					cursor: pointer;
					padding: 2px 5px;
					overflow: hidden;
					text-overflow:ellipsis;
					white-space: nowrap;
					&.active {
						background: rgba(172,230,175,.7);
						color: #fff;
						border-radius: 4px;
					}
				}
			}
		}
		.menu-fixed {
			position: fixed;
			top: 25px;
		}

		@media (max-width: 991px) {
			.menu-fixed {
				display: none;
			}
			.records-bg {
				.cbp_tmtimeline {
					>li {
						.cbp_tmtime,.cbp_tmicon {
							display: none;
						}
						.cbp_tmlabel {
							margin-left: 0;
							.cbp_tmlabel_title {
								&:after {
									display: none;
								}
							}
						}
					}
					&:before {
						display: none;
					}
				}
			}
		}

		@media (min-width: 992px) {
			.menu-fixed {
				display: block;
				top: 25px;
		    	width: 212.5px;
			}
			.records-bg {
				.cbp_tmtimeline {
					>li {
						.cbp_tmtime,.cbp_tmicon {
							display: block;
						}
						.cbp_tmlabel {
							margin-left: 180px;
							.cbp_tmlabel_title {
								&:after {
									display: block;
								}
							}
						}
					}
					&:before {
						display: block;
					}
				}
			}
		}
		@media (min-width: 1200px) {
			.menu-fixed {
				left: auto;
				top: 20px;
				width: 262.5px;
			}
		}
	}
</style>